import axios from "axios";
import http from "./request-old";
import { message } from "ant-design-vue";

//修改附件
export const updateAttach = (FileInfo) =>
  http.post("/alvin/sysAttachFiles/updateAttach", FileInfo);

//删除附件
export const deleteAttach = (attachId) =>
  http.get(`/alvin/sysAttachFiles/deleteAttach/${attachId}`);

//下载附件api
export const downloadAttachApi = (attachId) =>
  http.getByExport(`/alvin/sysAttachFiles/downloadAttach/${attachId}`);

//获取附件列表
export const querySysAttachFilesByBusiness = (tableName, mark, relaId) =>
  http.get("/alvin/sysAttachFiles/querySysAttachFilesByBusiness", {
    tableName,
    mark,
    relaId,
  });

//上传附件
export const vlrrUploadAttach = (files, param, apiUrl) => {
  return new Promise((resolve, reject) => {
    //处理数据
    let formData = new FormData();
    for (let key in param) {
      formData.append(key, param[key]);
    }
    files.forEach((file: any) => {
      formData.append("file", file as any);
    });
    console.log(formData);
    //配置头
    const request = axios.create({
      headers: {
        accessToken: localStorage.getItem("accessToken"),
        "Content-Type": "multipart/form-data",
      },
      responseType: "blob",
    });
    //开始上传
    return request
      .post(apiUrl, formData)
      .then((response: any) => {
        if (response.data && response.data.type === "application/vnd.ms-excel") {
          resolve(response.data);
        } else if (response.data.code !== "0") {
          //错误码处理
          if (response.data.type === "application/json") {
            let reader = new FileReader();
            reader.onload = function () {
              let res = reader.result;
              let result = JSON.parse(res); // blob格式转成json
              resolve(result);
            };
            reader.readAsText(response.data);
          } else {
            http.interceptErrorCode(response, resolve, reject);
            reject(response);
          }
        } else {
          //正常处理
          resolve(response.data);
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};

//上传附件
export const uploadAttach = (
  files,
  param,
  apiUrl = "/alvin/sysAttachFiles/uploadAttach"
) => {
  return new Promise((resolve, reject) => {
    //处理数据
    let formData = new FormData();
    for (let key in param) {
      formData.append(key, param[key]);
    }
    files.forEach((file: any) => {
      formData.append("file", file as any);
    });
    console.log(formData);
    //配置头
    const request = axios.create({
      headers: {
        accessToken: localStorage.getItem("accessToken"),
        "Content-Type": "multipart/form-data",
      },
    });
    //开始上传
    return request
      .post(apiUrl, formData)
      .then((response: any) => {
        if (response.data.code !== "0") {
          //错误码处理
          http.interceptErrorCode(response, resolve, reject);
          reject(response);
        } else {
          //正常处理
          resolve(response.data);
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};

//Inspection Rules导入
export const importIqcRule = (files, name, apiUrl) => {
  // debugger
  apiUrl = "/alvin/iqcmasterdata/" + apiUrl;
  //处理数据
  let formData = new FormData();
  // files.forEach((file: any) => {
  formData.append("file", files[0]);
  // })
  console.log("formData", formData);
  //配置头
  const request = axios.create({
    headers: {
      accessToken: localStorage.getItem("accessToken"),
      "Content-Type": "multipart/form-data",
    },
    responseType: "arraybuffer",
  });
  //开始上传
  return request
    .post(apiUrl, formData)
    .then((res) => {
      console.log("then下载res", res);
      doFileDownload(res.data, name);
    })
    .catch((res) => {
      console.log("下载res", res);
      doFileDownload(res.data, name);
    });
};

//下载方法
export const downloadAttach = (record) => {
  record.downLoading = true;
  downloadAttachApi(record.tid)
    .then((res) => {
      doFileDownload(res, record);
      delete record.downLoading;
    })
    .catch((res) => {
      doFileDownload(res, record);
      delete record.downLoading;
    });
};

export const doFileDownload = (res, record) => {
  if (res.hasOwnProperty("code")) {
    message.error(res.msg);
  } else {
    const content = res; // 拿到file流
    console.log("content", content);
    const blob = new Blob([content], { type: "application/vnd.ms-excel" }); //new Blob构造函数 转化链接使得可以直接在客户端上创建和操作 Blob(可下载文件）
    const fileName = typeof record === "object" ? record.originName : record; //添加后缀,指定要变成什么格式的文件
    const link = document.createElement("a");
    link.style.display = "none";
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    document.body.appendChild(link); // 此写法兼容可火狐浏览器
    link.click();
    URL.revokeObjectURL(link.href); // 释放URL 对象
    document.body.removeChild(link);
    message.success("附件下载成功");
  }
};
